package com.zzyl.nursing.service.impl;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import cn.hutool.json.JSONUtil;
import com.aliyun.iot20180120.Client;
import com.aliyun.iot20180120.models.*;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.zzyl.common.constant.CacheConstants;
import com.zzyl.common.core.domain.AjaxResult;
import com.zzyl.common.exception.base.BaseException;
import com.zzyl.common.utils.DateUtils;
import com.zzyl.common.utils.StringUtils;
import com.zzyl.framework.config.properties.AliIoTConfigProperties;
import com.zzyl.nursing.dto.DeviceDto;
import com.zzyl.nursing.vo.DeviceVo;
import com.zzyl.nursing.vo.ProductVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import com.zzyl.nursing.mapper.DeviceMapper;
import com.zzyl.nursing.domain.Device;
import com.zzyl.nursing.service.IDeviceService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.transaction.annotation.Transactional;

import static java.awt.SystemColor.info;

/**
 * 设备Service业务层处理
 * 
 * @author alexis
 * @date 2024-11-12
 */
@Service
public class DeviceServiceImpl extends ServiceImpl<DeviceMapper, Device> implements IDeviceService
{
    @Autowired
    private DeviceMapper deviceMapper;

    @Autowired
    private Client client;

    @Autowired
    private AliIoTConfigProperties aliIoTConfigProperties;

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    /**
     * 查询设备
     * 
     * @param id 设备主键
     * @return 设备
     */
    @Override
    public Device selectDeviceById(Long id)
    {
        return getById(id);
    }

    /**
     * 查询设备列表
     * 
     * @param device 设备
     * @return 设备
     */
    @Override
    public List<Device> selectDeviceList(Device device)
    {
        return deviceMapper.selectDeviceList(device);
    }

    /**
     * 新增设备
     * 
     * @param device 设备
     * @return 结果
     */
    @Override
    public int insertDevice(Device device)
    {
        return save(device) ? 1 : 0;
    }

    /**
     * 修改设备
     * 
     * @param device 设备
     * @return 结果
     */
    @Override
    public int updateDevice(Device device)
    {
        return updateById(device) ? 1 : 0;
    }

    /**
     * 批量删除设备
     * 
     * @param ids 需要删除的设备主键
     * @return 结果
     */
    @Override
    public int deleteDeviceByIds(Long[] ids)
    {
        return removeByIds(Arrays.asList(ids)) ? 1 : 0;
    }

    /**
     * 删除设备信息
     * 
     * @param id 设备主键
     * @return 结果
     */
    @Override
    public int deleteDeviceById(Long id)
    {
        return removeById(id) ? 1 : 0;
    }

    /**
     * 从IOT平台同步产品列表到redis中
     */
    @Override
    public void syncProductList() {
        // 1. 调用IOT平台接口，获取产品列表
        QueryProductListRequest queryProductListRequest = new QueryProductListRequest();
        queryProductListRequest.setCurrentPage(1);
        queryProductListRequest.setPageSize(100);
        queryProductListRequest.setIotInstanceId(aliIoTConfigProperties.getIotInstanceId());

        QueryProductListResponse response;
        try {
            response = client.queryProductList(queryProductListRequest);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }

        // 判断是否请求成功
        if (!response.getBody().getSuccess()) {
            throw new BaseException("调用IOT平台获取产品列表失败");
        }

        // 2. 将产品列表保存到redis中
        List<QueryProductListResponseBody.QueryProductListResponseBodyDataListProductInfo> productInfo = response.getBody().getData().getList().getProductInfo();
        redisTemplate.opsForValue().set(CacheConstants.IOT_PRODUCT_LIST, JSONUtil.toJsonStr(productInfo));
    }

    /**
     * 从Redis中获取所有产品列表
     *
     * @return 产品列表
     */
    @Override
    public List<ProductVo> allProduct() {
        String productListStr = redisTemplate.opsForValue().get(CacheConstants.IOT_PRODUCT_LIST);

        if (StringUtils.isEmpty(productListStr)) {
            // 响应一个空集合
            return Collections.emptyList();
        }

        // 将字符串转为List集合对象
        return JSONUtil.toList(productListStr, ProductVo.class);
    }

    /**
     * 注册设备到IOT平台和数据库表
     *
     * @param deviceDto 设备信息
     */
    @Override
    public void addDevice(DeviceDto deviceDto) {
        // 1.判断设备名称是否重复
        Long count = deviceMapper.selectCount(Wrappers.<Device>lambdaQuery().eq(Device::getDeviceName, deviceDto.getDeviceName()));
        if (count > 0) {
            // 重复了
            throw new BaseException("该设备名称已存在");
        }

        // 2.如果不重复，则调用IOT平台接口，注册设备
        RegisterDeviceRequest registerDeviceRequest = deviceDto.getRegisterDeviceRequest();
        registerDeviceRequest.setIotInstanceId(aliIoTConfigProperties.getIotInstanceId());

        RegisterDeviceResponse response;
        try {
            response = client.registerDevice(registerDeviceRequest);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }

        if (!response.getBody().success) {
            throw new BaseException("调用IOT平台注册设备失败");
        }

        // 获取结果中的iot_id
        String iotId = response.getBody().getData().getIotId();

        // 3.查询IOT平台获取产品信息（名称），将产品名称保存到设备对象
        QueryProductRequest queryProductRequest = new QueryProductRequest();
        queryProductRequest.setIotInstanceId(aliIoTConfigProperties.getIotInstanceId());
        queryProductRequest.setProductKey(deviceDto.getProductKey());

        QueryProductResponse queryProductResponse;
        try {
            queryProductResponse = client.queryProduct(queryProductRequest);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }

        if (!queryProductResponse.getBody().success) {
            throw new BaseException("调用IOT平台查询产品信息失败");
        }

        // 产品信息查询成功
        String productName = queryProductResponse.getBody().getData().getProductName();

        // 属性拷贝
        Device device = BeanUtil.toBean(deviceDto, Device.class);
        device.setProductName(productName);
        // 设置iotId
        device.setIotId(iotId);

        // 4.判断位置类型是否是0，如果是0，设置物理位置类型为-1（老人）
        if (device.getLocationType() == 0) {
            device.setPhysicalLocationType(-1);
        }

        try {
            // 5.保存设备到数据库
            save(device);
        } catch (Exception e) {
            // 6.判断是否保存成功，如果保存失败了，则删除IOT平台设备
            DeleteDeviceRequest deleteDeviceRequest = new DeleteDeviceRequest();
            deleteDeviceRequest.setDeviceName(deviceDto.getDeviceName());
            deleteDeviceRequest.setProductKey(deviceDto.getProductKey());
            deleteDeviceRequest.setIotId(iotId);
            deleteDeviceRequest.setIotInstanceId(aliIoTConfigProperties.getIotInstanceId());
            try {
                client.deleteDevice(deleteDeviceRequest);
            } catch (Exception ex) {
                throw new BaseException("调用IOT平台删除设备失败");
            }
            throw new BaseException("该老人/位置已绑定该产品，请重新选择");
        }
    }

    /**
     * 查询设备详情
     *
     * @param deviceDto 设备信息
     * @return 设备详情
     */
    @Override
    public DeviceVo queryDeviceDetail(DeviceDto deviceDto) {
        // 1.根据产品key和设备id查询IOT平台获取设备信息
        QueryDeviceDetailRequest request = new QueryDeviceDetailRequest();
        request.setProductKey(deviceDto.getProductKey());
        request.setIotId(deviceDto.getIotId());
        request.setIotInstanceId(aliIoTConfigProperties.getIotInstanceId());

        QueryDeviceDetailResponse response;
        try {
            response = client.queryDeviceDetail(request);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }

        // 获取响应中的设备信息
        if (!response.getBody().success) {
            throw new BaseException("调用IOT平台查询设备详情失败");
        }

        QueryDeviceDetailResponseBody.QueryDeviceDetailResponseBodyData data = response.getBody().getData();

        // 2.根据设备id查询数据库获取数据库中的设备信息
        Device device = deviceMapper.selectOne(Wrappers.<Device>lambdaQuery()
                .eq(Device::getIotId, deviceDto.getIotId()));

        // 3.合并两部分数据
        DeviceVo deviceVo = BeanUtil.toBean(device, DeviceVo.class);
        BeanUtil.copyProperties(data, deviceVo, CopyOptions.create().ignoreNullValue());

        // 4.返回合并后的结果数据
        return deviceVo;
    }

    /**
     * 查看指定产品的已发布的物模型中的功能定义详情
     *
     * @param request 请求对象，包含了productKey
     * @return 结果
     */
    @Override
    public AjaxResult queryThingModelPublished(QueryThingModelPublishedRequest request) {
        request.setIotInstanceId(aliIoTConfigProperties.getIotInstanceId());

        // 1.调用IOT平台接口查询结果
        QueryThingModelPublishedResponse response;
        try {
            response = client.queryThingModelPublished(request);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }

        if (!response.getBody().success) {
            throw new BaseException("调用IOT平台查询已发布物模型失败");
        }

        // 2.查询成功，返回结果
        return AjaxResult.success(response.getBody().getData());
    }

    /**
     * 查询指定设备的物模型运行状态
     *
     * @param request 请求对象，包含了设备名称和productKey
     * @return 结果
     */
    @Override
    public AjaxResult queryDevicePropertyStatus(QueryDevicePropertyStatusRequest request) {
        request.setIotInstanceId(aliIoTConfigProperties.getIotInstanceId());

        QueryDevicePropertyStatusResponse response;
        try {
            response = client.queryDevicePropertyStatus(request);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }

        if (!response.getBody().success) {
            throw new BaseException("调用IOT平台查询设备物模型运行状态失败");
        }

        // 获取IOT平台返回的结果，返回给前端
        return AjaxResult.success(response.getBody().getData());
    }

    /**
     * 修改设备备注名称
     *
     * @param device 新的设备对象
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateDeviceNickname(Device device) {
        // 1.修改数据库中的设备名称
        deviceMapper.updateById(device);

        // 2.修改IOT平台上的设备名称
        BatchUpdateDeviceNicknameRequest request = new BatchUpdateDeviceNicknameRequest();
        request.setIotInstanceId(aliIoTConfigProperties.getIotInstanceId());
        List<BatchUpdateDeviceNicknameRequest.BatchUpdateDeviceNicknameRequestDeviceNicknameInfo> list = new ArrayList<>();

        BatchUpdateDeviceNicknameRequest.BatchUpdateDeviceNicknameRequestDeviceNicknameInfo nicknameInfo = new BatchUpdateDeviceNicknameRequest.BatchUpdateDeviceNicknameRequestDeviceNicknameInfo();
        nicknameInfo.setNickname(device.getNickname());
        nicknameInfo.setProductKey(device.getProductKey());
        nicknameInfo.setDeviceName(device.getDeviceName());

        list.add(nicknameInfo);
        request.setDeviceNicknameInfo(list);

        BatchUpdateDeviceNicknameResponse response;
        try {
            response = client.batchUpdateDeviceNickname(request);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }

        if (!response.getBody().success) {
            throw new BaseException("调用IOT平台修改设备备注名称失败");
        }
    }
}
